using System;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using MCMLXVII.Core.Common;
using MCMLXVII.Core.Common.BackEnd;
using MCMLXVII.BackEnd.Pipeline;
using MCMLXVII.BackEnd.Listeners;


namespace MCMLXVII.BackEnd.Listeners
{
    public partial class BackendService : ServiceBase
    {

        private bool _TraceOn = false;
        private ConsoleSync Sync;

        public BackendService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Sync = new ConsoleSync();
            Sync.OnStart(Int32.Parse(Configuration.Instance.GetSystemParameter("TCPPort")));            
            Tracer.GetInstance().HostTrace += new HostTraceEventHandler(HostTrace_EventHandler);
            Tracer.StartHostTrace(MCMLXVII.Core.Common.BackEnd.TraceLevel.Info, false);
            _TraceOn = true;


            Tracer.StopHostTrace();
            _TraceOn = false;


        }

        protected override void OnStop()
        {
            Sync.OnEnd();
            Sync = null;
        }


        private bool ProcessCommand(string CommandInput)
        {
            string[] CommandInp = CommandInput.Split(new char[] { '/' });
            string stCommand = CommandInp[0].Trim().ToLower();
            string stActionName = "";
            if (CommandInp.Length > 1)
                stActionName = CommandInp[1].Trim();

            switch (stCommand)
            {
                    case "traceon":
                            _TraceOn = true;
                            Tracer.StartHostTrace(MCMLXVII.Core.Common.BackEnd.TraceLevel.Verbose, false);
                        break;
                    case "traceoff": 
                            _TraceOn = false;
                            Tracer.StopHostTrace();
                        break;
            }
            return false;
        }

        private void HostTrace_EventHandler(object sender, HostTraceEventArgs e)
        {
            if (_TraceOn)
            {
                if (!e.IsActionEvent())
                    Sync.PublishServiceEvent(e.Info);
                else
                    Sync.PublishActionEvent(e.ActionName, e.ActionID, e.Info);
            }
        }



    }
}
